package com.example.kwokg.meishi.Activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;

import com.example.kwokg.meishi.Bean.Content;
import com.example.kwokg.meishi.Constants;
import com.example.kwokg.meishi.R;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONArray;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;

public class VideoActivity extends AppCompatActivity {

    private Content content;
    private Button btn;
    private String username;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_video);

        //初始化view
        initView();

        //拿到传过来的数据，判断不为空即可设置VideoView
        VideoView vv = (VideoView) findViewById(R.id.vv);
        Intent intent = getIntent();
        content = (Content) intent.getSerializableExtra("video");
        String video= content.getVideo();
        if (video!=null){
            vv.setVideoURI(Uri.parse(video));
            vv.setMediaController(new MediaController(this));
            vv.start();
        }
//        查询是否收藏
        initCollect();

    }

    private void initView() {
        btn = (Button) findViewById(R.id.btn_collect);
        btn.setClickable(true);
        btn.setText("收藏");
        username = getSharedPreferences("name", MODE_PRIVATE).getString("name", null);
    }

    private void initCollect() {
        BmobQuery query=new BmobQuery("Content");
        query.addWhereEqualTo("video",content.getVideo());
        query.addWhereEqualTo("userMark",username);
        query.findObjectsByTable(new QueryListener<JSONArray>() {
            @Override
            public void done(JSONArray jsonArray, BmobException e) {
                if (!jsonArray.toString().equals("[]")){
                    btn.setText("已收藏");
                    btn.setClickable(false);
                }
            }
        });
    }

    public void collect(View view) {
        if (username==null){
            //没有登录就先去登录
            Toast.makeText(VideoActivity.this, "请先登录", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this,Login.class));
            overridePendingTransition(0,0);
            finish();
        }
        //给收藏添加用户标记后放入数据库
        content.setUserMark(username);
        content.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e==null){
                    Toast.makeText(VideoActivity.this, "收藏成功", Toast.LENGTH_SHORT).show();
                    downloadVideo();
                    initCollect();
                }else{
                    Toast.makeText(VideoActivity.this, "收藏失败~请检查网络", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    //简单实现下下载
    private void downloadVideo() {
        OkHttpClient client=new OkHttpClient();
        Request request=new Request.Builder().url(content.getVideo()).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
            }

            @Override
            public void onResponse(Response response) throws IOException {
                byte[] bytes = response.body().bytes();
                File file=new File(Constants.APP_ROOTPATH + content.getRecommend_caption() + ".mp4");
                Log.i("Tag",content.getRecommend_caption()+"----------"+this.getClass().getSimpleName());
                FileOutputStream outputStream = new FileOutputStream(file);
                outputStream.write(bytes);
                outputStream.close();
            }
        });
    }
}
